﻿namespace Blaze.Editor.LuaExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Framework.LuaExtensions;

    internal static class LuaScriptSourceResolver
    {
        public static ILuaScriptSource Resolve(LuaBehaviour behaviour)
        {
            if (behaviour == null)
                return null;
            ILuaScriptSource source;
            if (mMap.TryGetValue(behaviour.GetType(), out source))
                return source;

            var behaviourType = behaviour.GetType();
            var query = from type in Assembly.GetExecutingAssembly().GetTypes()
                let attribute = (CustomScriptSourceAttribute) type.GetCustomAttributes(typeof(CustomScriptSourceAttribute), false).FirstOrDefault()
                where attribute != null && attribute.TargetType == behaviourType
                select type;
            var sourceType = query.FirstOrDefault();
            if (sourceType == null)
                source = new DefaultLuaScriptSource();
            else
                source = (ILuaScriptSource) Activator.CreateInstance(sourceType);
            mMap.Add(behaviour.GetType(), source);
            return source;
        }

        private static readonly Dictionary<Type, ILuaScriptSource> mMap = new Dictionary<Type, ILuaScriptSource>();
    }
}